//
// Created by LiuYou on 2021/8/12.
//

#include <csignal>
#include <cstdio>
#include <cstring>
#include <sys/socket.h>
#include <cassert>
#include <netinet/in.h>
#include <cstdlib>
#include <arpa/inet.h>
#include <unistd.h>
#include "SocketAPI01.hpp"


static bool stop = false;

static void sigtermHandler(int sig) {
    stop = true;
}


/**
 * backlog参数对listen系统调用的实际影响。
 */
int main(int argc, char** argv) {
    signal( SIGTERM, sigtermHandler );

    if (argc < 4) {
        fprintf( stderr, "用法: %s ip port backlog\n", basename( argv[0] ));
        return 1;
    }

    char* ip = argv[1];
    char* port = argv[2];
    char* backlog = argv[3];

    int socketFd = socket( PF_INET, SOCK_STREAM, 0 );
    assert( socketFd >= 0 );

    sockaddr_in localAddress = {
            .sin_family=AF_INET,
            .sin_port=htons( atoi( port ))
    };
    inet_pton( AF_INET, ip, &localAddress.sin_addr );

    int ret = bind( socketFd, (sockaddr*) &localAddress, sizeof( localAddress ));
    assert( ret != -1 );

    ret = listen( socketFd, atoi( backlog ));
    assert( ret != -1 );

    // 循环等待连接, 直到有SIGTERM信号将它中断。
    while (!stop) {
        sleep( 1 );
    }


    close( socketFd );

    return 0;
}































